package edu.hubu.controller;

import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

/**
 * @author moonlan
 * date 2020/11/12 23:41
 */
@SuppressWarnings(value = "unused")
@RestController
@RequestMapping("/img")
public class ImgController {

    @PostMapping("/upload")
    public void imgUpload(@RequestParam("file") MultipartFile file) {
        if (!file.isEmpty()) {
            try {
                // 文件存放服务端的位置
                File rootPath = new File(ResourceUtils.getURL("classpath:").getPath());
                File dir = new File(rootPath.getAbsolutePath(), "static/");
                if (!dir.exists()) {
                    boolean mkdirs = dir.mkdirs();
                }
                // 写文件到服务器
                File serverFile = new File(dir.getAbsolutePath() + File.separator + file.getOriginalFilename());
                file.transferTo(serverFile);
            } catch (Exception ignored) {
            }
        }
    }

}
